package com.lzb.newloan;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzb.newloan.adapter.OverduePhoneListAdapter;
import com.lzb.newloan.pojo.PersonPojo;
import com.lzb.newloan.utils.AlertDialog;
import com.lzb.newloan.utils.BaseActivity;
import com.lzb.newloan.utils.Config;
import com.lzb.newloan.utils.Formatdou;
import com.lzb.newloan.utils.HttpUtils;
import com.lzb.newloan.utils.TimeUtils;
import com.lzb.newloan.xlistview.XListView;
import com.lzb.newloan.xlistview.XListView.IXListViewListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 我要催收
 */
public class OverduePhoneActivity extends BaseActivity implements
		OnClickListener, IXListViewListener {

	private XListView list_overdue_phone;
	private ArrayList<PersonPojo> arrayList;
	private OverduePhoneListAdapter adapter;
	private String userId;
	private String contactphone02;
	private String contactphone;
	private String mobilephone;
	private double sjsh_money;
	private double sjds_money;
	private int yuq_ts;
	private String cardusername;
	private double all_lx;
	private double yuq_lx;

	protected int curPage;
	protected boolean isloadMore;
	private String jkid,idnoStr;
	private TextView name;
	private TextView day;
	private TextView all_money


			;
	private TextView name_phone;
	private TextView name_phone1;
	private TextView name_phone2;
	private RelativeLayout contact;
	private TextView user;
	private RelativeLayout contact2;
	private RelativeLayout contact1;
	private TextView record;
	private TextView money;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_overdue_phone);
		initView();
		initData();
	}
	private Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case Config.CODE_OVERDUEPHONE:
					String reString = msg.obj.toString();
					try {
						JSONObject response = new JSONObject(reString);
						JSONObject overdueUser = response
								.getJSONObject("overdueUser");
						cardusername = overdueUser
								.getString("cardusername");
						name.setText(cardusername);
						name_phone.setText(cardusername);
						idnoStr = overdueUser.getString("idno");
						idnoStr = idnoStr.substring(0,3)+"**********"+idnoStr.substring((idnoStr.length())-4,idnoStr.length());
						yuq_ts = overdueUser.getInt("over_days");
						day.setText("逾期：" + yuq_ts + "天");

						sjsh_money = overdueUser.getDouble("actual_amount");
						money.setText("本金:"+ Formatdou.formatdou(sjsh_money));
						String contactname = overdueUser
								.getString("contactname");
						mobilephone = overdueUser.getString("mobilephone");
						yuq_lx = overdueUser.getDouble("over_moeny");
						all_lx = sjsh_money+ yuq_lx;
						all_money.setText("总利息:" + Formatdou.formatdou(yuq_lx));

						contactphone = overdueUser
								.getString("contactphone");
						name_phone1.setText(contactname + ":"
								+ contactphone);
						contactphone02 = overdueUser
								.getString("contactphone02");
						String contactname02 = overdueUser
								.getString("contactname02");
						name_phone2.setText(contactname02 + ":"
								+ contactphone02);
						JSONObject pageObject = response
								.getJSONObject("page");
						// int totalPages = pageObject.getInt("totalPages");
						// if (curPage < totalPages) {
						// list_overdue_phone.setPullLoadEnable(true);
						// } else {
						// list_overdue_phone.setPullLoadEnable(false);
						// }
						JSONArray data = pageObject.getJSONArray("data");
						for (int i = 0; i < data.length(); i++) {
							PersonPojo pojo = new PersonPojo();
							JSONObject object = (JSONObject) data.get(i);
							pojo.setPhone(object.getString("peer_number"));
							pojo.setCardusername(pojo.getPhone() + "通话次数["
									+ object.getString("geshu") + "]");
							pojo.setHk_money(sjsh_money);
							pojo.setDay(yuq_ts);
							pojo.setJkPhone(mobilephone);
							pojo.setJkName(cardusername);
							arrayList.add(pojo);
						}
						if (yuq_ts<=1) {
							contact.setVisibility(View.VISIBLE);
							record.setVisibility(View.GONE);
							user.setVisibility(View.GONE);
							contact1.setVisibility(View.GONE);
							contact2.setVisibility(View.GONE);
							list_overdue_phone.setVisibility(View.GONE);
						}else if(yuq_ts<=3&yuq_ts>1){
							contact.setVisibility(View.VISIBLE);
							record.setVisibility(View.GONE);
							user.setVisibility(View.VISIBLE);
							contact1.setVisibility(View.VISIBLE);
							contact2.setVisibility(View.VISIBLE);
							list_overdue_phone.setVisibility(View.GONE);
						}else if (yuq_ts>3) {
							contact.setVisibility(View.VISIBLE);
							record.setVisibility(View.VISIBLE);
							user.setVisibility(View.VISIBLE);
							contact1.setVisibility(View.VISIBLE);
							contact2.setVisibility(View.VISIBLE);
							list_overdue_phone.setVisibility(View.VISIBLE);
						}
						adapter.setArrayList(arrayList);
						adapter.notifyDataSetChanged();
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					break;
				case Config.CODE_URL_ERROR:
					Toast.makeText(OverduePhoneActivity.this, "url错误",
							Toast.LENGTH_SHORT).show();
					break;
				case Config.CODE_NET_ERROR:
					Toast.makeText(OverduePhoneActivity.this, "网络错误",
							Toast.LENGTH_SHORT).show();
					break;

				default:
					break;
			}
		};
	};

	private void initData() {
		HttpUtils.doPostAsyn(Config.OVERDUEPHONE_CORD + "&investorID="
				+ userId + "&borrowID=" + jkid, "",mHandler, Config.CODE_OVERDUEPHONE);
	}

	private void initView() {
		SharedPreferences sp = getSharedPreferences("config", 0x0000);
		userId = sp.getString("userid", "");
		jkid = getIntent().getStringExtra("id");
		RelativeLayout backpress = (RelativeLayout) findViewById(R.id.backpress);
		backpress.setOnClickListener(this);
		TextView title_txt_center = (TextView) findViewById(R.id.title_txt_center);
		title_txt_center.setText("我要催收");
		list_overdue_phone = (XListView) findViewById(R.id.list_overdue_phone);
		arrayList = new ArrayList<PersonPojo>();
		// for (int i = 0; i < 5; i++) {
		// BorrowPersonPojo pojo = new BorrowPersonPojo();
		// arrayList.add(pojo);
		// }
		adapter = new OverduePhoneListAdapter(this, arrayList, 3);
		list_overdue_phone.setAdapter(adapter);
		list_overdue_phone.setXListViewListener(this);
		list_overdue_phone.setPullLoadEnable(false);
		list_overdue_phone.setPullRefreshEnable(false);

		name = (TextView) findViewById(R.id.name);
		day = (TextView) findViewById(R.id.day);
		all_money = (TextView) findViewById(R.id.all_money);
		money = (TextView) findViewById(R.id.money);
		name_phone = (TextView) findViewById(R.id.name_phone);
		TextView send_msg = (TextView) findViewById(R.id.send_msg);
		send_msg.setOnClickListener(this);
		TextView call = (TextView) findViewById(R.id.call);
		call.setOnClickListener(this);
		name_phone1 = (TextView) findViewById(R.id.name_phone1);
		TextView send_msg1 = (TextView) findViewById(R.id.send_msg1);
		send_msg1.setOnClickListener(this);
		TextView call1 = (TextView) findViewById(R.id.call1);
		call1.setOnClickListener(this);
		name_phone2 = (TextView) findViewById(R.id.name_phone2);
		TextView send_msg2 = (TextView) findViewById(R.id.send_msg2);
		send_msg2.setOnClickListener(this);
		TextView call2 = (TextView) findViewById(R.id.call2);
		call2.setOnClickListener(this);
		
		contact = (RelativeLayout) findViewById(R.id.contact);
		user = (TextView) findViewById(R.id.user);
		contact2 = (RelativeLayout) findViewById(R.id.contact2);
		contact1 = (RelativeLayout) findViewById(R.id.contact1);
		record = (TextView) findViewById(R.id.record);
	}


	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// list.clear();
				curPage = 1;
				isloadMore = false;
				// initData(minmoney,maxmoney,sexperson);
				onLoad();
			}
		}, 2000);
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				curPage += 1;
				isloadMore = true;
				// initData(minmoney,maxmoney,sexperson);
				onLoad();
			}
		}, 2000);
	}

	protected void onLoad() {
		list_overdue_phone.stopRefresh();
		list_overdue_phone.stopLoadMore();
		list_overdue_phone.setRefreshTime(TimeUtils.getDate());
	}

	@Override
	public void processMessage(Message message) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.backpress:
			finish();
			break;
		case R.id.call:
			call(mobilephone);
			break;
		case R.id.call1:
			call(contactphone);
			break;
		case R.id.call2:
			call(contactphone02);
			break;
		case R.id.send_msg:
//			double money = yuq_lx + sjsh_money;
			String msg = "";
			if(yuq_ts<=1){
				msg="【钱宝包】"+cardusername+"您好，您的借款已经逾期"+yuq_ts+"天,当前应还款" + all_lx+"元，请及时处理避免影响征信和提额。";
			}else if(yuq_ts<=3||yuq_ts>=2){
				msg="【钱宝包】"+cardusername+"您好，您的借款已逾期"+yuq_ts+"天,当前应还款" + all_lx+"元，为了维护您的信誉和避免影响您的提额，造成额外的经济损失，麻烦请您尽快处理！特此提醒，感谢配合谢谢！";
			}else if(yuq_ts<=7||yuq_ts>3){
				msg = "【钱宝包】"+cardusername+"您好，您的借款已逾期"+yuq_ts+"天,当前应还款" + all_lx+"元，即将超过可提额的逾期天数，请您在1天内尽快处理，否则平台催收人员将按规定联系您的亲友进行催款，感谢配合！";
			}else if(yuq_ts<=10||yuq_ts>7){
				msg = "【钱宝包】"+cardusername+"您好，你的借款已经逾期"+yuq_ts+"天,当前应还款" + all_lx+"元，请及时处理避免影响征信。不接电话，屏蔽电话，不还款，根据规定将会联系你通讯录的联系人配合还款，如还款遇到问题尽快与催收人员联系。守点承诺，多点信用。";
			}else if(yuq_ts<=15||yuq_ts>10){
				msg="【钱宝包】"+cardusername+"您好（"+idnoStr+"）您的借款已逾期"+yuq_ts+"天,当前应还款" + all_lx+"元，您好，如果再不处理和回复，您本人借款资料及借款视频将进行征信黑名单系统以及发送您身边所有亲朋友好友，请勿涉及骗贷，以免严重者将走法律程序，请尽快处理！";
			}else if(yuq_ts<=18||yuq_ts>15){
				msg="【钱宝包】"+cardusername+"您好，您的借款已逾期"+yuq_ts+"天,当前应还款" + all_lx+"元，由于您一直不接电话，不回短信，我们即将以信件的方式把催收信邮寄到村委会(乡镇居委会)，由村委协助催收，以免让全村人知道您的借款情况，进入社会征信黑名单，造成将来您结婚生子困难，小孩上学被歧视，请你在1天内回复，感谢配合！";
			}else if(yuq_ts<=20|yuq_ts>18){
				msg="【钱宝包】"+cardusername+"您好，你已经逾期"+yuq_ts+"天,当前应还款" + all_lx+"元，请及时还款避免影响征信。不接电话，屏蔽电话，不还款，属于恶意欠款，根据规定会联系你通讯录的联系人，拨打半年来有效通话记录，并发送你的借款视频给其相对应的微信配合还款。请慎重对待，尽快联系催收人员，避免引起不必要的影响。守点承诺，多点信用。";
			}else{
				msg="【钱宝包】您的借款已逾期" + yuq_ts + "天,当前应还款" + all_lx+"元，由于您的本次借款逾期非常严重，经平台多次提醒和告知无效，现已经构成恶意拖欠行为,如继续拖欠借款，平台将公布您的个人信息并移交法律部联系您户籍地村委会，如造成一切不良影响，后果自负!";
			}
			sendMsg(msg,	mobilephone);
			break;
		case R.id.send_msg1:
			String msg1="";
			if(yuq_ts<=7){
				msg1="【钱宝包】您好，您的亲友"+cardusername+"("+mobilephone+")申请的借款已逾期"+yuq_ts+"天,当前应还款"+all_lx+"元。"+cardusername+"申请借款时授权我们将您作为可协助的联系人，烦请您转告"+cardusername+"尽快还款，以免再次打扰，谢谢！";
			}else{
				msg1="【钱宝包】您好，您的亲友"+cardusername+"（"+idnoStr+"）申请的借款已逾期"+yuq_ts+"天，当前应还款"+ all_lx + "元。由于他一直不接电话，不回短信，我们即将以信件的方式把催收信邮寄到他所在的居委会、村委，由居委会、村委协助催收，" +
						"以免让大家都知道他的借款情况，进入社会征信黑名单，造成他出行不便，小孩上学被歧视等等，请帮忙转达，感谢配合！";
			}
			sendMsg(msg1, contactphone);
			break;
		case R.id.send_msg2:
			String msg2="";
			if(yuq_ts<=7){
				msg2="【钱宝包】您好，您的亲友"+cardusername+"("+mobilephone+")申请的借款已逾期"+yuq_ts+"天，当前应还款"+all_lx+"元。"+cardusername+"申请借款时授权我们将您作为可协助的联系人，烦请您转告"+cardusername+"尽快还款，以免再次打扰，谢谢！\n";
			}else{
				msg2="【钱宝包】您好，您的亲友"+cardusername+"（"+idnoStr+"）申请的借款已逾期"+yuq_ts+"天，当前应还款"+ all_lx + "元。由于他一直不接电话，不回短信，我们即将以信件的方式把催收信邮寄到他所在的居委会、村委，由居委会、村委协助催收，" +
						"以免让大家都知道他的借款情况，进入社会征信黑名单，造成他出行不便，小孩上学被歧视等等，请帮忙转达，感谢配合！";
			}
			sendMsg(msg2, contactphone02);

			break;
		default:
			break;
		}
	}

	private void call(String tell) {
		startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tell)));
	}

	private void sendMsg(final String msg, final String tel) {
		AlertDialog dialog = new AlertDialog(this);
		dialog.builder();
		dialog.setMsg(msg);
		dialog.setNegativeButton("暂不发送", new OnClickListener() {
			@Override
			public void onClick(View v) {

			}
		});
		dialog.setPositiveButton("立即发送", new OnClickListener() {

			@Override
			public void onClick(View v) {
				Uri smsToUri = Uri.parse("smsto:" + tel);

				Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
				if (msg.contains(contactphone)||msg.contains(contactphone02)) {
					intent.putExtra("sms_body", msg.substring(0, msg.length()-11));
				}else {
					intent.putExtra("sms_body", msg);
				}
				
				startActivity(intent);
			}
		});
		dialog.show();
	}

}
